import 'package:flutter/material.dart';
import '../../../models/message.dart';
import '../../../utils/avatar_utils.dart';

class MessageBubble extends StatelessWidget {
  final Message message;
  final String? avatarUrl;
  final String? contactName;
  final VoidCallback? onAvatarTap;

  const MessageBubble({
    super.key,
    required this.message,
    this.avatarUrl,
    this.contactName,
    this.onAvatarTap,
  });

  @override
  Widget build(BuildContext context) {
    final isMe = message.isMe;
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      child: Row(
        mainAxisAlignment:
            isMe ? MainAxisAlignment.end : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (!isMe) ...[
            _buildAvatar(),
            const SizedBox(width: 8),
          ],
          Flexible(
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
              decoration: BoxDecoration(
                color: isMe ? const Color(0xFF95EC69) : Colors.white,
                borderRadius: BorderRadius.circular(4),
              ),
              child: Text(
                message.content,
                style: const TextStyle(
                  fontSize: 16,
                  color: Colors.black,
                ),
              ),
            ),
          ),
          if (isMe) ...[
            const SizedBox(width: 8),
            _buildAvatar(),
          ],
        ],
      ),
    );
  }

  Widget _buildAvatar() {
    return GestureDetector(
      onTap: onAvatarTap,
      child: avatarUrl != null
          ? Container(
              width: 40,
              height: 40,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(4),
                image: DecorationImage(
                  image: NetworkImage(avatarUrl!),
                  fit: BoxFit.cover,
                ),
              ),
            )
          : buildInitialsAvatar(contactName ?? 'User', size: 40),
    );
  }
}
